package com.qilu.pe.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.blankj.utilcode.util.UriUtils;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qilu.pe.R;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Config;
import com.qilu.pe.base.Global;
import com.qilu.pe.base.MyApp;
import com.qilu.pe.dao.bean.Doctor;
import com.qilu.pe.dao.bean.ImageUrl;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.ActiviceCollector;
import com.qilu.pe.support.util.GlideUtil;
import com.qilu.pe.support.util.GlobalReqUtil;
import com.qilu.pe.support.util.Logg;
import com.qilu.pe.support.util.PeUtil;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.util.ToastUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;
import okhttp3.MultipartBody;

/**
 * <br/>┏------------------------------------------
 * <br/>│Note:
 * <br/>│
 * <br/>┣------------------------------------------
 * <br/>│                 /) /)
 * <br/>│               ฅ(• ﻌ •)ฅ
 * <br/>│  Created by @author HaoKing on 2020/11/10 16:50.
 * <br/>│          www.muchenxinxi.com
 * <br/>│           www.nextdever.com
 * <br/>│           WeChat: NextDever
 * <br/>│             QQ: 773693552
 * <br/>│     QQ Group: Geek Chat 344386592
 * <br/>┗------------------------------------------
 */
public class EditMyInfoActivity extends Activity implements View.OnClickListener {

    private RoundedImageView vAvatar;
    private TextView vName, vJob, vIdCardNo, vGender, vWorkAge;

    private String mId;
    private String mAvatarUrl = "";
    private String mGender = "0";
    private String mWorkAge = "0";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_my_info);
        ActiviceCollector.addActivity(this);
        initView();
        initData();
    }

    public void initView() {
        vAvatar = findViewById(R.id.vAvatar);
        vAvatar.setOnClickListener(this);
        vName = findViewById(R.id.vName);
        vJob = findViewById(R.id.vJob);
        vIdCardNo = findViewById(R.id.vIdCardNo);
        vWorkAge = findViewById(R.id.vWorkAge);
        vWorkAge.setOnClickListener(this);
        vGender = findViewById(R.id.vGender);
        vGender.setOnClickListener(this);
        findViewById(R.id.vSubmit).setOnClickListener(this);
        findViewById(R.id.vBack).setOnClickListener(this);
    }

    public void initData() {
        mId = getIntent().getStringExtra("id");
        APIRetrofit.getDefault().getDoctorDetail(Global.HEADER, mId)
                .compose(RxUtil.<BaseResult2<Doctor>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<Doctor>>() {
                    @Override
                    public void accept(BaseResult2<Doctor> res) throws Exception {
                        if (res.isSuccess()) {
                            Doctor doctor = res.getData();
                            GlideUtil.loadImg(PeUtil.getImageUrl(doctor.getPicture()), vAvatar);
                            mAvatarUrl = doctor.getPicture();

                            vGender.setText("0".equals(doctor.getSex()) ? "男" : "女");
                            mGender = doctor.getSex();

                            vJob.setText(!TextUtils.equals("1", doctor.getIs_admin()) ? "负责人" : "医生");

                            vName.setText(doctor.getName());
                            vWorkAge.setText(doctor.getYear());
                            mWorkAge = doctor.getYear();
                            vIdCardNo.setText(doctor.getIdentity());
                        } else {
                            ToastUtils.showShort(res.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.vBack:
                finish();
                break;
            case R.id.vAvatar:
                ImagePicker.getInstance().setSelectLimit(1);
                Intent intent = new Intent(this, ImageGridActivity.class);
                startActivityForResult(intent, 1901);
                break;
            case R.id.vWorkAge:
                OptionsPickerView workAgePicker = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        vWorkAge.setText(String.valueOf(options1));
                        mWorkAge = String.valueOf(options1);
                    }
                }).build();
                List<String> workAgeList = new ArrayList<>();
                for (int i = 0; i < 100; i++) {
                    workAgeList.add(String.valueOf(i));
                }
                workAgePicker.setPicker(workAgeList);
                workAgePicker.show();
                break;
            case R.id.vGender:
                OptionsPickerView genderPicker = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        if (options1 == 0) {
                            mGender = "0";
                        } else {
                            mGender = "1";
                        }
                        vGender.setText("0".equals(mGender) ? "男" : "女");
                    }
                }).build();
                List<String> genderList = new ArrayList<>();
                genderList.add("男");
                genderList.add("女");
                genderPicker.setPicker(genderList);
                genderPicker.show();
                break;
            case R.id.vSubmit:
                if (vName.getText().toString().trim().isEmpty()) {
                    ToastUtils.showShort("请输入姓名");
                } else {
                    APIRetrofit.getDefault().editMyInfo(Global.HEADER, mId, mAvatarUrl, vName.getText().toString().trim(), mGender, mWorkAge)
                            .compose(RxUtil.<BaseResult2>subIoObMain())
                            .subscribe(new Consumer<BaseResult2>() {
                                @Override
                                public void accept(BaseResult2 res) throws Exception {
                                    if (res.isSuccess()) {
                                        ToastUtils.showShort("保存成功");
                                        finish();
                                    } else {
                                        ToastUtils.showShort(res.getMsg());
                                    }
                                }
                            }, new Consumer<Throwable>() {
                                @Override
                                public void accept(Throwable throwable) throws Exception {
                                    throwable.printStackTrace();
                                }
                            });
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 1901) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images.size() > 0) {
                    Logg.e("images.get(0).uri.getPath() = " + images.get(0).uri.getPath());
//                    MultipartBody body = GlobalReqUtil.generateMultipartBody("id", new File(images.get(0).uri.getPath()));
//                    File file= UriUtils.uri2File(images.get(0).uri);
                    File file= new File(images.get(0).uri.getPath());
                    MultipartBody.Part part = GlobalReqUtil.generateMultipartBody("picture", file);
                    GlobalReqUtil.reqUploadImage(part, new GlobalReqUtil.OnReqCallBack() {
                        @Override
                        public void onReqResult(BaseResult2<List<ImageUrl>> baseResult2) {
                            if (baseResult2.isSuccess()) {
                                mAvatarUrl = Config.URL_IMG + baseResult2.getData().get(0).getImg();
                                Logg.e("==修改头像=="+mAvatarUrl);
                                GlideUtil.loadImg(mAvatarUrl, vAvatar);
                            }
                        }

                        @Override
                        public void onReqException(Throwable throwable) {
                            throwable.printStackTrace();
                        }
                    });
                }
            }
        }
    }

}
